import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { AuthService } from '../auth.servics';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { User } from './User';

@Component({
  selector: 'app-login-component',
  templateUrl: './login-component.component.html',
  styleUrls: ['./login-component.component.css']
})
export class LoginComponentComponent implements OnInit {
  myForm: FormGroup;
  userName: FormControl;
  password: FormControl;
  baseUrl = 'http://127.0.0.1:8080/';
  users$: Observable<User[]>;


  constructor(private authService: AuthService, private fb: FormBuilder, private httpClient: HttpClient) {
    this.myForm = this.fb.group({
      'userName': [''],
      'password': [''],
    });
    this.users$ = <Observable<User[]>>this.httpClient.get(this.baseUrl + 'users');
    this.userName = <FormControl>this.myForm.controls['userName'];
    this.password = <FormControl>this.myForm.controls['password'];
  }

  ngOnInit(): void {
  }

  login() {
          this.httpClient.post(this.baseUrl + 'login', this.myForm.value).subscribe(
            (val: any) => {
              if (val.succ) {
                console.log(val.succ)
              } else {
                alert('密码错误');
                this.authService.logout();
                window.location.href = "http://localhost:4200/";

              }
            });
      this.authService.login();
  }

}
